﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Role;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System.Security.Cryptography.X509Certificates;

namespace B.S.BasicData.Api.Write.Application.Handler.Role
{
    public class UpdateRoleHandler : IRequestHandler<UpdateRoleCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IMapper mapper;

        public UpdateRoleHandler(IBaseRepository<RoleModel> roleRepo,IMapper mapper)
        {
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var role = roleRepo.GetAll().Where(x => x.RoleName == request.RoleName && x.Id!=request.Id && x.IsDelete==false).FirstOrDefault();
            var roles = roleRepo.GetAll().Where(x => x.RoleName == request.RoleName && x.Id != request.Id && x.IsDelete == false).Count();
            if (roles == 1)
            {
                res.Msg = "角色已存在";
                res.Code=ApiEnum.Error;
                return Task.FromResult(res);
            }
            else
            {
                role = mapper.Map(request, role);
                role.UpdateName = "李四";
                role.UpdateTime= DateTime.Now;
                role.CreateTime = DateTime.Now;
                role.CreateName = "张三";
                var i=roleRepo.Update(role);
                if (i>0)
                {
                    res.Msg = "修改成功";
                    res.Code = ApiEnum.Success;
                    res.Data = i;
                }
                else
                {
                    res.Msg = "修改失败";
                    res.Code = ApiEnum.Error;
                    res.Data = i;
                }
                return Task.FromResult(res);
            }
        }
    }
}
